-- 
function get_host(volume_id)
	local key = 'volume.host.'..volume_id
	local fs = ngx.shared.fs

	local host = fs.get(fs, key)
	if host ~= nil then
		return host
	end
	local url = 'http://localhost:9333/dir/lookup?volumeId='..ngx.var.volume_id..'&pretty=y'
	
	local ok, html = get_html(url)
	if ok then
		local cjson = require('cjson')
		local data = cjson.decode(html)
		if data.locations ~= nil and data.locations[1] ~= nil and data.locations[1].publicUrl then
			host = data.locations[1].publicUrl
			fs.set(fs, key, host, 3600*24)
			return host
		end
	end
	return nil
end

function get_html(url, c)
	local curl = require('luacurl')
    local result = { }
    if c == nil then
        c = curl.new()
    end
    c:setopt(curl.OPT_URL, url)
    c:setopt(curl.OPT_WRITEDATA, result)
    c:setopt(curl.OPT_WRITEFUNCTION, function(tab, buffer)     --call back函数，必须有
        table.insert(tab, buffer)                      --tab参数即为result，参考http://luacurl.luaforge.net/

        return #buffer
    end)
    local ok = c:perform()
    return ok, table.concat(result)             --此table非上一个table，作用域不同
end

if ngx.var.img_type == 'orig' then
	local host = get_host(ngx.var.volume_id)
	if host ~= nil then
		local pos = string.len('/orig/')
		local uri = string.sub(ngx.var.uri, pos)
		ngx.req.set_uri(uri)
		ngx.var.new_host = host
	else
		ngx.exit(404)
	end
elseif ngx.var.img_type == 'crop' then
	local pos = string.len('/orig/')
	local uri = string.sub(ngx.var.uri, pos)

	pos = string.find(uri, "([-])")
	local ruri = string.sub(uri, 0, pos - 1)
	pos = string.find(uri, "([.])")
	ruri = ruri..string.sub(uri, pos)
	--print(ruri)

	local path = ngx.var.image_root..'/orig'..ruri
	local newpath = ngx.var.image_root..'/crop'..uri
	--print(newpath)
	--[[
	if io.open(newpath, 'r') ~= nil then
		ngx.req.set_body_file(newpath)
	end
	]]

	if io.open(path, 'r') == nil then
		--print('dir=`dirname '..path..'`;if [ ! -d $dir ];then mkdir -m 0777 -p $dir;fi');
		os.execute('dir=`dirname '..path..'`;if [ ! -d $dir ];then mkdir -m 0777 -p $dir;fi')
		local ret = ngx.location.capture('/orig'..ruri);
		--print(ret.body)
		local f = io.open(path, 'w')
		f:write(ret.body)
		f:close()
	end
	area = ngx.var.img_width..'x'..ngx.var.img_height
	--print('dir=`dirname '..newpath..'`;if [ ! -d $dir ];then mkdir -m 0777 -p $dir;fi');
	os.execute('dir=`dirname '..newpath..'`;if [ ! -d $dir ];then mkdir -m 0777 -p $dir;fi')
	local command = "/usr/local/bin/gm convert "..
		path..
		" -resize "..area.."^"..
		" -crop "..area..
		" -background white -gravity center -extent "..area.." "..newpath;
	print(command)
	os.execute(command)
end